package com.maigao.service;

import com.maigao.core.exception.ServerCode;
import com.maigao.core.exception.ServerException;
import com.maigao.entity.form.AddUserForm;
import com.maigao.entity.jpa.Coach;
import com.maigao.entity.jpa.Student;
import com.maigao.entity.jpa.User;
import com.maigao.entity.vo.CoachVO;
import com.maigao.entity.vo.StudentVO;
import com.maigao.entity.vo.UserVO;
import com.maigao.persistent.CoachRepository;
import com.maigao.persistent.StudentRepository;
import com.maigao.persistent.UserRepository;
import com.maigao.util.CollectionUtils;
import com.maigao.util.DateUtils;
import com.maigao.util.Md5Util;
import com.maigao.util.uuid.IdUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: maigao
 * @description:
 * @author: yongza
 * @create: 2024-10-16 23:48
 **/
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private CoachRepository coachRepository;

    public Pair<Boolean, String> bindRegistrationCode(String mobile, String registrationCode) {
        if (StringUtils.isAnyBlank(mobile, registrationCode)) {
            return Pair.of(false, "参数不完整!");
        }
        User user = userRepository.findByMobileAndRegistrationCode(mobile, registrationCode);
        if (null == user) {
            return Pair.of(false, "手机号和注册码不匹配!");
        }
        if (StringUtils.isNotBlank(user.getWxOpenId())) {
            return Pair.of(false, "当前注册码已经绑定过微信, 不支持重复绑定!");
        }
        return Pair.of(true, user.getUid());
    }

    public Triple<Boolean, String, User> tryAddUser(AddUserForm addUserForm) {
        if (StringUtils.isAnyBlank(addUserForm.getUserName(), addUserForm.getMobile())) {
            return Triple.of(false, "用户名或手机号不能为空!", null);
        }
        User oldUser = userRepository.findByMobile(addUserForm.getMobile());
        if (null != oldUser) {
            return Triple.of(false, "手机号已被注册!", null);
        }
        User user = initUser();
        user.setUserName(addUserForm.getUserName());
        user.setMobile(addUserForm.getMobile());
        if (null == User.UserType.getByValue(addUserForm.getUserType())) {
            return Triple.of(false, "非法用户类型!", null);
        }
        user.setUserType(addUserForm.getUserType());
        String registrationCode = createRegistrationCode(addUserForm.getUserName(), addUserForm.getMobile(),
                addUserForm.getUserType());
        user.setRegistrationCode(registrationCode);
        userRepository.save(user);
        return Triple.of(true, "", user);
    }

    public User findUserByWxOpenId(String wxOpenId) {
        return userRepository.findByWxOpenIdAndUserStatus(wxOpenId, User.UserStatus.NORMAL.getValue());
    }

    public User findUserByUid(String uid) {
        return userRepository.findByUid(uid);
    }

    public UserVO findUserDetailByMobile(String mobile) {
        User user = findUserByMobile(mobile);
        UserVO userVO = new UserVO();
        userVO.setCreateTime(DateUtils.format(user.getCreateTime(), DateUtils.Formatter.DATETIME_YYYY_MM_DD_HH_MM_SS));
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    public User findUserByMobile(String mobile) {
        return userRepository.findByMobile(mobile);
    }

    public Triple<Boolean, String, UserVO> findUserDetail(String uid) {
        User user = userRepository.findByUid(uid);
        if (null == user) {
            return Triple.of(false, "当前用户不存在!", null);
        }
        List<Student> students = studentRepository.findByUserUid(uid);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setIsStudent(false);
        userVO.setIsCoach(false);
        if (CollectionUtils.isNotEmpty(students)) {
            userVO.setIsStudent(true);
        }
        Coach coach = coachRepository.findByUserUid(uid);
        if (null != coach) {
            userVO.setIsCoach(true);
        }
        return Triple.of(true, "", userVO);
    }

    public Triple<Boolean, List<StudentVO>, String> findAllStudentByUid(String uid) {
        User user = userRepository.findByUid(uid);
        if (null == user) {
            return Triple.of(false, null, "当前用户不存在!");
        }
        List<Student> students = studentRepository.findByUserUid(uid);
        if (CollectionUtils.isEmpty(students)) {
            return Triple.of(false, null, "当前账号下没有创建学生!");
        }
        return Triple.of(true, convert2Detail(students), "");
    }

    public List<StudentVO> convert2Detail(List<Student> students) {
        List<StudentVO> studentVOS = new ArrayList<>();
        for (Student student : students) {
            StudentVO studentVO = new StudentVO();
            BeanUtils.copyProperties(student, studentVO);
            studentVO.setCreateTime(DateUtils.format(student.getCreateTime(), DateUtils.Formatter.DATETIME_YYYY_MM_DD_HH_MM_SS));
            Coach coach = coachRepository.findById(student.getCoachId());
            if (null != coach) {
                studentVO.setCoachMobile(coach.getMobile());
            }
            studentVOS.add(studentVO);
        }
        return studentVOS;
    }

    public Triple<Boolean, CoachVO, String> findCoachByUid(String uid) {
        User user = userRepository.findByUid(uid);
        if (null == user) {
            return Triple.of(false, null, "当前用户不存在!");
        }
        Coach coach = coachRepository.findByUserUid(uid);
        if (null == coach) {
            return Triple.of(false, null, "当前账号下没有教练!");
        }
        CoachVO coachVO = new CoachVO();
        BeanUtils.copyProperties(coach, coachVO);
        coachVO.setCreateTime(DateUtils.format(coach.getCreateTime(), DateUtils.Formatter.DATETIME_YYYY_MM_DD_HH_MM_SS));
        return Triple.of(true, coachVO, "");
    }

    public Pair<Boolean, String> upgrade2Admin(Integer coachId) {
        Coach coach = coachRepository.findById(coachId);
        if (null == coach) {
            return Pair.of(false, "当前教练不存在");
        }
        User user = userRepository.findByUid(coach.getUserUid());
        if (null == user) {
            return Pair.of(false, "查询用户信息失败");
        }
        if (user.getUserStatus() == User.UserStatus.DISABLED.getValue()) {
            return Pair.of(false, "当前用户已被禁用, 不支持升级");
        }
        user.setUserType(User.UserType.ADMIN.getValue());
        userRepository.save(user);
        return Pair.of(true, "");
    }

    public Pair<Boolean, String> reduce2Normal(String uid) {
        User user = userRepository.findByUid(uid);
        if (null == user) {
            return Pair.of(false, "查询用户信息失败");
        }
        if (user.getUserStatus() == User.UserStatus.DISABLED.getValue()) {
            return Pair.of(false, "当前用户已被禁用, 不支持升级");
        }
        user.setUserType(User.UserType.NORMAL.getValue());
        userRepository.save(user);
        return Pair.of(true, "");
    }

    public UserVO queryUserDetailInfo(int id, String uid) {
        User user;
        if (StringUtils.isBlank(uid)) {
            user = userRepository.findById(id);
        } else {
            user = userRepository.findByUid(uid);
        }
        if (null == user) {
            throw new ServerException(ServerCode.FORBIDDEN);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setCreateTime(DateUtils.format(user.getCreateTime(), DateUtils.Formatter.DATETIME_YYYY_MM_DD_HH_MM_SS));
        userVO.setIsStudent(false);
        userVO.setIsCoach(false);
        List<Student> students = studentRepository.findByUserUid(user.getUid());
        if (CollectionUtils.isNotEmpty(students)) {
            userVO.setIsStudent(true);
        }
        Coach coach = coachRepository.findByUserUid(user.getUid());
        if (null != coach) {
            userVO.setIsCoach(true);
        }
        return userVO;
    }

    /**
     * 初始化
     */
    public User initUser() {
        User userInfoEntity = new User();
        userInfoEntity.setUid(IdUtils.fastSimpleUUID());
        userInfoEntity.setUserStatus(User.UserStatus.NORMAL.getValue());
        userInfoEntity.setUserType(User.UserType.NORMAL.getValue());
        userInfoEntity.setCreateTime(LocalDateTime.now());
        return userInfoEntity;
    }

    public String createRegistrationCode(String userName, String mobile, Integer userType) {
        return Md5Util.getMD5String(String.format("%s:%s:%s:", userName, mobile, userType)).toLowerCase();
    }
}
